<template xmlns:background-color="http://www.w3.org/1999/xhtml">
  <a-row :gutter="10">
    <a-col :md="6" :sm="24">
      <a-card :bordered="false">
        <!-- 按钮操作区域 -->
        <a-row style="margin-left: 14px">
          <a-button v-show="!treeData.length" @click="handleAdd(1)" type="primary">添加车场组</a-button>
        </a-row>
        <div style="background: #fff; padding-left: 16px; height: 100%; margin-top: 5px">
          <a-input-search
            v-model="searchKey"
            @search="onSearch"
            style="width: 100%; margin-top: 10px"
            placeholder="请输入车场组名称"
          />
          <!-- 树-->
          <a-col :md="10" :sm="24">
            <template>
              <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
                <span style="user-select: none">
                  <a-tree
                    :selectedKeys="selectedKeys"
                    :checkedKeys="checkedKeys"
                    :checkStrictly="true"
                    @select="onSelect"
                    @check="onCheck"
                    @rightClick="rightHandle"
                    @expand="onExpand"
                    v-if="treeData.length"
                    :tree-data="treeData"
                    :default-expanded-keys="this.keyId"
                  />
                </span>
                <!--新增右键点击事件,和增加添加和删除功能-->
                <a-menu slot="overlay">
                  <a-menu-item v-show="orgType == 0 || orgType == 1" @click="handleAdd(3)" key="1"
                    >添加子架构</a-menu-item
                  >
                  <a-menu-item v-show="orgType == 1 || orgType == 2" @click="handleAdd(4)" key="4"
                    >添加同级架构</a-menu-item
                  >
                  <a-menu-item @click="handleAdd(5)" key="5">添加用户</a-menu-item>
                  <a-menu-item v-show="orgType == 2" @click="handleAdd(6)" key="6">添加车场</a-menu-item>
                  <a-menu-item v-show="orgType != 3" @click="handleAdd(7)" key="7">修改</a-menu-item>
                  <a-menu-item v-show="orgType != 0 && orgType != 3" key="2">
                    <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete()">
                      <a>删除</a>
                    </a-popconfirm>
                  </a-menu-item>
                  <a-menu-item v-show="orgType == 3">
                    <a-popconfirm title="确定解绑吗?" @confirm="() => handleDelete()">
                      <a>解绑</a>
                    </a-popconfirm>
                  </a-menu-item>
                  <a-menu-item @click="closeDrop" key="3">取消</a-menu-item>
                </a-menu>
              </a-dropdown>
            </template>
          </a-col>
        </div>
      </a-card>
    </a-col>
    <a-col :md="18" :sm="24">
      <a-menu v-model="menuType" mode="horizontal">
        <a-menu-item key="mail" @click="menuList('user')">用户列表 </a-menu-item>
        <a-menu-item key="app" @click="menuList('carPark')"> 车场列表 </a-menu-item>
      </a-menu>
      <a-card :bordered="false">
        <a-table
          ref="table"
          bordered
          size="middle"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          @change="tableChange"
        >
          <template slot="avatarslot" slot-scope="text, record">
            <div class="anty-img-wrap">
              <a-avatar shape="square" :src="getAvatarView(record.avatar)" icon="user" />
            </div>
          </template>
            <span slot="action" slot-scope="text, record">
              <a>

                <a-popconfirm title="确定解绑吗?" @confirm="() => unbound(record)">
                      <a>解绑</a>
                    </a-popconfirm>
              </a>
            </span>
        </a-table>
      </a-card>
    </a-col>
    <depart-modal ref="departModal" @ok="newLoadTree"></depart-modal>
    <depart-modal2 ref="departModal2" @ok="newLoadTree"></depart-modal2>
  </a-row>
</template>
<script>
import DepartModal from './modules/DepartModal'
import DepartModal2 from './modules/DepartModal2'
import { queryDepartTreeList, searchByKeywords, deleteByDepartId } from '@/api/api'
import { httpAction, getAction, deleteAction, postAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
export default {
  name: 'DepartList',
  mixins: [JeecgListMixin],
  components: {
    DepartModal,
    DepartModal2,
  },
  data() {
    return {
      ipagination: {
        current: 1,
        pageSize: 10,
        //pageSizeOptions:['10','50','100'],
        showTotal: (total, range) => {
          //return range[0] + '-' + range[1] + '共' + total + '条'
          return '共' + total + '条'
        },
        showQuickJumper: false,
        showSizeChanger: false,
        total: 0,
      },
      dataSource: [],
      columns: [
        {
          title: '账号',
          dataIndex: 'username',
        },
        {
          title: '真实姓名',
          dataIndex: 'realname',
        },
        {
          title: '邮箱',
          dataIndex: 'email',
        },
        {
          title: '电话',
          dataIndex: 'phone',
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: {customRender: 'action'},
          align: 'center',
        },
      ],
      menuType: ['mail'],
      departTree: [],
      defaultExpandedKeys: [],
      ParkInfoList: [],
      iExpandedKeys: [],
      loading: false,
      currFlowId: '',
      currFlowName: '',
      disable: true,
      treeData: [],
      keyId: [],
      visible: false,
      rightClickSelectedKey: '',
      departName: '',
      hiding: true,
      model: {},
      dropTrigger: '',
      depart: {},

      disableSubmit: false,
      checkedKeys: [],
      selectedKeys: [],
      autoIncr: 1,
      currSelected: {},
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      graphDatasource: {
        nodes: [],
        edges: [],
      },
      validatorRules: {
        departName: { rules: [{ required: true, message: '请输入车场名称!' }] },
        orgCode: { rules: [{ required: true, message: '请输入车场编码!' }] },
        mobile: { rules: [{ validator: this.validateMobile }] },
      },
      url: {
        delete: '/sysdepart/sysDepart/delete',
        edit: '/sysdepart/sysDepart/edit',
        deleteBatch: '/sysdepart/sysDepart/deleteBatch',
        exportXlsUrl: 'sysdepart/sysDepart/exportXls',
        importExcelUrl: 'sysdepart/sysDepart/importExcel',
        getDeptAllNodeNameList: 'sysdepart/sysDepart/getDeptAllNodeNameList',
        getDeptAllNodeParkList: 'sysdepart/sysDepart/getDeptAllNodeParkList',
        unbound: 'sysdepart/sysDepart/unbound',
      },
      searchKey: '',
      timer: '',
      orgType: 0,
      selectKey: '',
      treeType: '',
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    tableChange(nextTargetKeys) {
      if(this.treeType == null || this.treeType == '' || this.treeType == 'user'){
        this.deptAllNodeNameList(this.selectKey || null, nextTargetKeys.current)
      }else{
        this.deptAllNodeParkList(this.selectKey || null, nextTargetKeys.current)
      }
    },
    
    // 切换列表
    menuList(type) {
      this.treeType = type;
      let _self = this
      let action = {
        // 车场列表显示
        carPark: function () {
          _self.deptAllNodeParkList(_self.selectKey || null)
          _self.dataSource = this.dataSource
          _self.columns = [
            {
              title: '车场名称',
              dataIndex: 'departName',
            },
            {
              title: '车场编号',
              dataIndex: 'parkCode',
            },
            {
              title: '联系电话',
              dataIndex: 'mobile',
            },
            {
              title: '操作',
              dataIndex: 'action',
              scopedSlots: {customRender: 'action'},
              align: 'center',
            },
          ]
        },
        // 用户列表显示
        user: function () {
          _self.deptAllNodeNameList(_self.selectKey || null)
          _self.dataSource = this.dataSource
          _self.columns = [
            {
              title: '账号',
              dataIndex: 'username',
            },
            {
              title: '绑定车场组',
              dataIndex: 'departName',
            },
            {
              title: '邮箱',
              dataIndex: 'email',
            },
            {
              title: '电话',
              dataIndex: 'phone',
            },
            {
              title: '操作',
              dataIndex: 'action',
              scopedSlots: {customRender: 'action'},
              align: 'center',
            },
          ]
        },
      }
      action[type]()
    },

    initParkInfoList() {
      getAction('/parking/parkInfo/parkInfoList').then((res) => {
        if (res.success) {
          this.ParkInfoList = res.result
        } else {
        }
      })
    },
    loadData() {
      this.refresh()
    },

    newLoadTree() {
      this.treeData = []
      this.loadTree()
    },

    // 查询点击节点下所有绑定用户
    deptAllNodeNameList(selectId, current = 1) {
      if(selectId == null || selectId.length == 0){
        return
      }
      let that = this
      let id = selectId[0]
      that.selectKey = selectId
      postAction(`${that.url.getDeptAllNodeNameList}?selectId=${id}&pageNo=${current}`).then((res) => {
        if (res.success) {
          that.dataSource = res.result.records
          that.ipagination.total = res.result.total
          that.ipagination.current = res.result.current
        } else {
          that.$message.warning(res.message)
        }
      })
    },

    // 查询点击节点下所有绑定车场
    deptAllNodeParkList(selectId, current = 1) {
      if(selectId == null || selectId.length == 0){
        return
      }
      let that = this
      let id = selectId[0]
      that.selectKey = selectId
      postAction(`${that.url.getDeptAllNodeParkList}?selectId=${id}&pageNo=${current}`).then((res) => {
        if (res.success) {
          that.dataSource = res.result.records
          that.ipagination.total = res.result.total
          that.ipagination.current = res.result.current
        } else {
          that.$message.warning(res.message)
        }
      })
    },

    unbound(record){
      let treeType = this.treeType;
      if(treeType != null && treeType != '' && treeType == 'carPark'){
        this.handleDelete(record.id)
        return
      }

      let that = this;
      var params = {
        id:record.id,
        depId:record.depId
      };
      postAction(that.url.unbound,params).then((res) => {
        if (res.success) {
          that.deptAllNodeNameList(this.selectKey || null, that.ipagination.current)
           that.$message.success(res.message)
        } else {
          that.$message.warning(res.message)
        }
      })
    },

    loadTree() {
      const that = this
      queryDepartTreeList().then((res) => {
        if (res.success) {
          let temp = []
          res.result.forEach((res) => {
            temp.push(res)
            that.treeData = temp
            that.departTree = temp
            if (res.orgType == 0) {
              that.keyId.push(res.key)
            }
          })
          this.loading = false
        }
      })
    },
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    refresh() {
      this.loading = true
      this.onSearch(this.searchKey)
    },
    // 右键操作方法
    rightHandle(node) {
      window.localStorage.setItem('deptId',node.node.dataRef.id);
      this.dropTrigger = 'contextmenu';
      this.orgType = node.node.dataRef.orgType;
      this.departName = node.node.dataRef.departName;
      this.rightClickSelectedKey = node.node.eventKey;
    },
    onExpand(expandedKeys) {
      this.iExpandedKeys = expandedKeys
    },
    backFlowList() {
      this.$router.back(-1)
    },
    // 右键点击下拉框改变事件
    dropStatus(visible) {
      if (visible == false) {
        this.dropTrigger = ''
      }
    },
    // 右键店家下拉关闭下拉框
    closeDrop() {
      this.dropTrigger = ''
    },
    addRootNode() {
      this.$refs.nodeModal.add(this.currFlowId, '')
    },
    batchDel: function () {
      if (this.checkedKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
      } else {
        var ids = ''
        for (var a = 0; a < this.checkedKeys.length; a++) {
          ids += this.checkedKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '确定要删除所选中的 ' + this.checkedKeys.length + ' 条数据?',
          onOk: function () {
            deleteAction(that.url.deleteBatch, { ids: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadTree()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          },
        })
      }
    },
    onSearch(value) {
      let that = this
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = window.setTimeout(() => {
        if (value) {
          searchByKeywords({ keyWord: value }).then((res) => {
            if (res.success) {
              that.treeData = []
              that.departTree = []
              for (let i = 0; i < res.result.length; i++) {
                let temp = res.result[i]
                that.departTree.push(temp)
                that.treeData.push(temp)
              }
            } else {
              that.$message.warning(res.message)
            }
          })
        } else {
          that.loadTree()
        }
        clearTimeout(this.timer)
      }, 1000)
    },
    nodeModalOk() {
      this.loadTree()
    },
    nodeModalClose() {},
    hide() {
      this.visible = false
    },
    onCheck(checkedKeys, info) {
      this.hiding = false
      this.checkedKeys = checkedKeys.checked
    },
    onSelect(selectedKeys, e) {
      let treeType = this.treeType;
      if(treeType == null || treeType == '' || treeType == 'user'){
        this.deptAllNodeNameList(selectedKeys)
      }else{
        this.deptAllNodeParkList(selectedKeys)
      }

      this.hiding = false
      let record = e.node.dataRef
      this.currSelected = Object.assign({}, record)
      this.model = this.currSelected
      this.selectedKeys = [record.key]
      this.model.parentId = record.parentId
    },
    getCurrSelectedTitle() {
      return !this.currSelected.title ? '' : this.currSelected.title
    },
    onClearSelected() {
      this.hiding = true
      this.checkedKeys = []
      this.currSelected = {}
      this.form.resetFields()
      this.selectedKeys = []
    },
    handleNodeTypeChange(val) {
      this.currSelected.nodeType = val
    },
    notifyTriggerTypeChange(value) {
      this.currSelected.notifyTriggerType = value
    },
    receiptTriggerTypeChange(value) {
      this.currSelected.receiptTriggerType = value
    },
    submitCurrForm() {
      this.form.validateFields((err, values) => {
        if (!err) {
          if (!this.currSelected.id) {
            this.$message.warning('请点击选择要修改车场!')
            return
          }

          let formData = Object.assign(this.currSelected, values)
          httpAction(this.url.edit, formData, 'put').then((res) => {
            if (res.success) {
              this.$message.success('保存成功!')
              this.loadTree()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    emptyCurrForm() {
      this.form.resetFields()
    },
    nodeSettingFormSubmit() {
      this.form.validateFields((err, values) => {
        if (!err) {
        }
      })
    },
    openSelect() {
      this.$refs.sysDirectiveModal.show()
    },
    handleAdd(num) {
      if (num == 1) {
        if (this.treeData.length >= 1) {
          this.$message.warning('车场组已存在！')
          return
        }
        this.$refs.departModal2.add()
        this.$refs.departModal2.title = '添加架构'
      } else if (num == 2) {
        let key = this.currSelected.key
        if (!key) {
          this.$message.warning('请先选中一条记录!')
          return false
        }
        this.$refs.departModal.add(this.selectedKeys)
        this.$refs.departModal.title = '新增'
      } else {
        let modelTitle = {
          3: '添加子架构',
          4: '添加同级架构',
          5: '添加用户',
          6: '添加车场',
          7: '修改',
        }
        this.$refs.departModal.add({
          parentId: this.rightClickSelectedKey,
          type: num,
          departName: this.departName,
          deptId: this.deptId,
        })
        this.$refs.departModal.title = modelTitle[num]
      }
    },
    handleDelete(parkId) {
      let id = this.rightClickSelectedKey
      if(parkId != null && parkId != '' && parkId != 'undefined'){
        id = parkId;
      }
      deleteByDepartId({ id: id }).then((resp) => {
        if (resp.success) {
          this.$message.success('删除成功!');
          this.newLoadTree();
          this.deptAllNodeParkList(this.selectKey);
        } else {
          this.$message.warning(resp.message)
        }
      })
    },
    selectDirectiveOk(record) {
      this.nodeSettingForm.setFieldsValue({ directiveCode: record.directiveCode })
      this.currSelected.sysCode = record.sysCode
    },
    getFlowGraphData(node) {
      this.graphDatasource.nodes.push({
        id: node.id,
        text: node.flowNodeName,
      })
      if (node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          let temp = node.children[a]
          this.graphDatasource.edges.push({
            source: node.id,
            target: temp.id,
          })
          this.getFlowGraphData(temp)
        }
      }
    },
  },
  created() {
    document.onkeydown = function (e) {
      let key = window.event.keyCode
      if (key === 13) {
      }
    }
    this.initParkInfoList()
    this.currFlowId = this.$route.params.id
    this.currFlowName = this.$route.params.name
    // this.loadTree()
    this.deptAllNodeNameList(null)
  },
}
</script>
<style scoped>
.ant-card-body .table-operator {
  margin: 15px;
}

.anty-form-btn {
  width: 100%;
  text-align: center;
}

.anty-form-btn button {
  margin: 0 5px;
}

.anty-node-layout .ant-layout-header {
  padding-right: 0;
}

.header {
  padding: 0 8px;
}

.header button {
  margin: 0 3px;
}

.ant-modal-cust-warp {
  height: 100%;
}

.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto;
}

.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden;
}

#app .desktop {
  height: auto !important;
}

/** Button按钮间距 */
.ant-btn {
  margin-left: 3px;
}
</style>